package cn.mystylefree.proxydemo.proxy;

import cn.mystylefree.proxydemo.dynamicproxy.DynamicProxyHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2022/07/14 20:00
 */
public class Main {
    //    public static void main(String[] args) {
//        HelloProxy helloProxy = new HelloProxy();
//        helloProxy.sayHello();
//    }

        public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //动态代理：实现方法1
//        Hello hello = new Hello();
//        InvocationHandler dynamicProxy = new DynamicProxy(hello);
//        Class<?> proxyClass = Proxy.getProxyClass(HelloInterface.class.getClassLoader(),
//                new Class<?>[]{HelloInterface.class});
//        Constructor<?> constructor = proxyClass.getConstructor(InvocationHandler.class);
//        HelloInterface instance = (HelloInterface)constructor.newInstance(dynamicProxy);
//        instance.sayHello();
        // 创建一个实例对象，这个对象是被代理的对象
        Hello hello = new Hello();
        ///创建一个与代理对象相关联的InvocationHandler
        InvocationHandler dynamicProxy = new DynamicProxyHandler(hello);
        //创建一个代理对象 proxyInstance 来代理z hello，代理对象的每个执行方法都会替换执行Invocation中的invoke方法
        HelloInterface proxyInstance = (HelloInterface) Proxy.newProxyInstance(
                dynamicProxy.getClass().getClassLoader(),
                hello.getClass().getInterfaces(),
                dynamicProxy);
        //执行代理中的方法
        proxyInstance.sayHello();
    }

//    public static void main(String[] args) {
//        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Student.class.getInterfaces());
//        String path = "G:/javacode/javase/Test/bin/proxy/StuProxy.class";
//        try(FileOutputStream fos = new FileOutputStream(path)) {
//            fos.write(classFile);
//            fos.flush();
//            System.out.println("代理类class文件写入成功");
//        } catch (Exception e) {
//            System.out.println("写文件错误");
//        }
//    }
}

